﻿#include "dbconnector.h"
#include "common.h"
#include<iostream>
#include<QVariant>
#include<QSqlRecord>


DBConnector::DBConnector()
{
    sqldb = QSqlDatabase::addDatabase("QSQLITE");

}


DBConnector::~DBConnector(){
    sqldb.close();
}

bool DBConnector::connect(const std::string  &dbName)
{

    sqldb.setDatabaseName(QString::fromStdString(dbName));
    if(!sqldb.open()){
        //TODO wrong log
        return false;
    }
    QSqlQuery query;
    if (query.exec("select * from sqlite_master  WHERE type = 'TABLE' and name = 'KVTABLE'")){
        if (!query.next()){
            QSqlQuery query1;
            if (!query.exec("create table \"KVTABLE\" (KVKEY TEXT PRIMARY KEY NOT NULL,KVALUE TEXT)")){

            }else{

            }
        }
    }
    return true;
}

bool DBConnector::checkConn()
{
    return sqldb.isOpen();
}

bool DBConnector::setValue(const std::string &key,const std::string  &value){
    if (this->ifExit(key)){
        //TODO LOG
        QSqlQuery query;
        query.prepare("UPDATE KVTABLE SET KVALUE = :VALUE WHERE KVKEY = :KEY ");
        query.bindValue(":VALUE",QVariant(QString::fromStdString(value.data())));
        query.bindValue(":KEY",QVariant(QString::fromStdString(key.data())));
        if (!query.exec()){
            //TODO wrong log
            return false;
        }
    }else{
        QSqlQuery query;
        query.prepare("INSERT INTO KVTABLE VALUES (:KEY,:VALUE)");
        query.bindValue(":KEY",QVariant(QString::fromStdString(key)));
        query.bindValue(":VALUE",QVariant(QString::fromStdString(value)));
        if (!query.exec()){
            //TODO wrong log
            return false;
        }

    }

    std::cout<<"set value:"<<std::endl;
    std::cout<<value<<std::endl;
    return true;
}


bool DBConnector::ifExit(const std::string &key){
    QSqlQuery query;
    query.prepare("select * from KVTABLE where kvkey = :KEY");
    query.bindValue(":KEY",QVariant(QString::fromStdString(key)));

    if(!query.exec()){
        //TODO log
        return false;
    }
    if(query.next()){
        return true;
    }else{
        return false;
    }
}

std::string DBConnector::getValue(const std::string &key){
    QSqlQuery query;
    query.prepare("select (K.KVALUE) from KVTABLE K where kvkey = :KEY");
    query.bindValue(":KEY",QVariant(QString::fromStdString(key)));
    query.exec();
    if(query.next()){
        return query.value(0).toString().toStdString();
    }else{
        return "";
    }

}

